package com.hong.utils.executors;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Auther: Administrator
 * @Date: 2018/7/30 18:37
 * @Description:
 */
public class CompletableFutureExample1 {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

     /*   Future<?> future = executorService.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        while (!future.isDone()){

        }
        System.out.println("DONE");*/

       /* CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).whenComplete((v,t)-> System.out.println("DONE"));
        System.out.println("===========i am not blocked=========");
        Thread.currentThread().join();*/

        List<Callable<Integer>> tasks = IntStream.range(0, 10).boxed().map(i -> (Callable<Integer>) () -> get()).collect(Collectors.toList());

        executorService.invokeAll(tasks).stream().map(future->{
            try {
                return  future.get();
            } catch (Exception e) {
               throw new RuntimeException(e);
            }
        }).parallel().forEach(CompletableFutureExample1::display);
    }

    private static void display(Integer data) {
        int value = ThreadLocalRandom.current().nextInt(20);
        try {
            System.out.println(Thread.currentThread().getName()+ "will be sleep "+value);
            TimeUnit.SECONDS.sleep(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ " execute done"+data);
    }

    private static int get(){
        int value = ThreadLocalRandom.current().nextInt(20);
        try {
            System.out.println(Thread.currentThread().getName()+ "will be sleep "+value);
            TimeUnit.SECONDS.sleep(value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ " execute done"+value);
        return  value;
    }
}
